package com.sun.module_common.webview

import ToolbarHeight
import android.content.res.ColorStateList
import android.view.ViewGroup
import android.webkit.WebView
import android.widget.FrameLayout
import android.widget.ProgressBar
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import com.sun.module_base.ext.dp2px
import com.sun.module_common.model.WebModel
import com.sun.module_common.widget.AppBar
import com.sun.module_common_res.R

/**
 *@author:sunc
 *@time :2025/8/11 15:48
 *@desc: 描述
 */

@Composable
fun WebScreen(
    modifier: Modifier = Modifier,
    webData: WebModel? = null,
    onBack: () -> Unit = {}
) {
    var ctrl: WebCtrl? by remember { mutableStateOf(null) }

//    OptimizedStatusBar(yellow)

    Box {
        AndroidView(
            modifier = modifier
                .fillMaxSize()
                .padding(top = ToolbarHeight),
            factory = { context ->
                FrameLayout(context).apply {
                    layoutParams = FrameLayout.LayoutParams(
                        FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT
                    )
                    val progressBar = ProgressBar(context).apply {
                        layoutParams = ViewGroup.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            dp2px(2f)
                        )
                        progressDrawable =
                            ContextCompat.getDrawable(context, R.drawable.horizontal_progressbar)
                        indeterminateTintList =
                            ColorStateList.valueOf(ContextCompat.getColor(context, R.color.grey_cd))
                    }
                    val webView = WebView(context).apply {
                        layoutParams = ViewGroup.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT
                        )
                    }
                    addView(webView)
                    addView(progressBar)
                    ctrl = WebCtrl(this, webData?.linkUrl ?: "", onWebCall = { isFinish ->

                    })
                    ctrl?.initSettings()
                }
            },
            update = {})
        AppBar(title = webData?.title ?: "标题", onBack = {
            onBack.invoke()
        })
    }
}